package com.example.myactspringboot.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

/**
 * @Create 2023-09-23 07:42
 * @Description
 */
@Configuration
public class ShiroConfig {
    //shirofilterfactorybean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        /*
        anon 无需认证就可以访问
        authc 必须认证才能访问
        user 必须拥有 记住我  功能才能用
        perms  拥有对某个资源的权限才能访问
        role  拥有某个角色权限才能访问
        */
        LinkedHashMap<String, String> lm = new LinkedHashMap<String, String>();
        lm.put("/user/add","perms[user:add]");
        lm.put("/user/update","perms[user:update]");
        lm.put("/login", "anon");
        lm.put("/doLogin", "anon"); //登录验证请求1
        lm.put("/static/**","anon");
        lm.put("/js/**", "anon");
        lm.put("/image/**", "anon");
        lm.put("/css/**", "anon");
        lm.put("/excel/**", "anon");
        lm.put("/**","authc");
//        lm.put("/modeler/**","authc");
//        lm.put("/**","anon");
        shiroFilterFactoryBean.setLoginUrl("/");
//        shiroFilterFactoryBean.setUnauthorizedUrl("/unAuthorized");
        shiroFilterFactoryBean.setUnauthorizedUrl("/");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(lm);
        return shiroFilterFactoryBean;

    }
    //2defaultWebSecurityManager
    @Bean(name = "defaultWebSecurityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userReal") UserReal userReal){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联realm类
        securityManager.setRealm(userReal);
        return securityManager;
    }
    //1创建realm 对象，需要自定义类
    @Bean(name = "userReal")
    public UserReal userReal(){
        return new UserReal();
    }
    //避免第一次访问400
    @Bean(name = "dws")
    public DefaultWebSessionManager getSessionManager() {
        DefaultWebSessionManager dws = new DefaultWebSessionManager();
        dws.setSessionIdUrlRewritingEnabled(false);
        return dws;
    }
/*    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }*/
}
